package util

import (
	"database/sql/driver"
	"errors"
	"fmt"
	"time"
)

const YyyyMmDdHhMmSs = "2006-01-02 15:04:05"
const YyyyMmDd = "2006-01-02"

func FormatDateTime(t time.Time) string {
	return t.Format(YyyyMmDdHhMmSs)
}

func FormatDate(t time.Time) string {
	return t.Format(YyyyMmDd)
}
func NowDateTimeStr() string {
	return time.Now().Format(YyyyMmDdHhMmSs)
}
func NowDateStr() string {
	return time.Now().Format(YyyyMmDd)
}

// Time 定义一个时间类型，指定JSON序列化和反序列化，sql Value和Scan
type Time struct {
	time.Time
}

// UnmarshalJSON 重写JSON反序列化
func (t *Time) UnmarshalJSON(data []byte) error {
	// Ignore null, like in the main JSON package.
	if string(data) == "null" {
		return nil
	}
	// Fractional seconds are handled implicitly by Parse.
	var err error
	now, err := time.Parse(`"`+YyyyMmDdHhMmSs+`"`, string(data))
	*t = Time{Time: now}
	return err
}

// MarshalJSON 重写JSON序列化
func (t Time) MarshalJSON() ([]byte, error) {
	if y := t.Year(); y < 0 || y >= 10000 {
		// RFC 3339 is clear that years are 4 digits exactly.
		// See golang.org/issue/4556#c15 for more discussion.
		return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]")
	}

	b := make([]byte, 0, len(YyyyMmDdHhMmSs)+2)
	b = append(b, '"')
	b = t.AppendFormat(b, YyyyMmDdHhMmSs)
	b = append(b, '"')
	return b, nil
}

// Value 实现：结构体 -> DB
func (t Time) Value() (driver.Value, error) {
	var zeroTime time.Time
	if t.Time.UnixNano() == zeroTime.UnixNano() {
		return nil, nil
	}
	return t.Time, nil
}

// Scan 实现：DB -> 结构体
func (t *Time) Scan(value interface{}) error {
	v, ok := value.(time.Time)
	if ok {
		*t = Time{Time: v}
		return nil
	}
	return fmt.Errorf("can not convert [ %v ] to util.Time", value)
}
